#
# fusion.db.invitation
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Friendship/membership invitations
"""

from __future__ import with_statement

import hmac
from hashlib import sha1
from binascii import hexlify, unhexlify
from zlib import compress, decompress
from os import urandom
import logging

import simplejson

from fusion.discovery import opendht
from fusion.lib.cipher import Cipher
from fusion.lib.sexp import encode, decode
from fusion.core.identity import generate, decode_identity
from fusion.core.item import decode_item, hex
from fusion.db.exceptions import Unauthorized

def _test_friendship_invitation():
    """
    >>> from fusion.db.db import DB, sync

    >>> db = DB()
    >>> p = db.create_persona()
    >>> code = db.create_friendship_invitation_code()
    >>> code is not None
    True

    >>> db2 = DB()
    >>> p2 = db2.create_persona()
    >>> i = db2.fetch_invitation(code)
    >>> i.iid == p
    True

    >>> sync(db, db2, p)
    >>> i.accept(db2)
    True

    >>> db2.list_friends(p) == [p2]
    True
    >>> db2.list_friends(p2) == [p]
    True

    >>> sync(db2, db)
    >>> db.list_friends(p) == [p2]
    True
    >>> db.list_friends(p2) == [p]
    True

    >>> db.fetch_invitation(code) is None
    True

    >>> db.close()
    >>> db2.close()
    """
    pass

def _test_membership_invitation():
    """
    >>> from fusion.db.db import DB, sync

    >>> db = DB()
    >>> p = db.create_persona()
    >>> g = db.create_group()
    >>> code = db.create_membership_invitation_code(g)
    >>> code is not None
    True

    >>> db2 = DB()
    >>> p2 = db2.create_persona()
    >>> i = db2.fetch_invitation(code)
    >>> i.iid == g
    True

    >>> sync(db, db2, g)
    >>> i.accept(db2)
    True

    >>> db2.list_memberships(p2) == [g]
    True
    >>> db2.list_members(g) == [p2]
    True
    >>> db2.list_members(g, verify=False) == [p, p2]
    True
    >>> sync(db, db2, p)
    >>> db2.list_members(g) == [p, p2]
    True

    >>> sync(db2, db)
    >>> db.list_members(g) == [p, p2]
    True

    >>> db.fetch_invitation(code) is None
    True

    >>> db.close()
    >>> db2.close()
    """
    pass

def create_friendship_invitation_code(db, **kwargs):
    obj = create_friendship_invitation(db, **kwargs)
    return stash_invitation(obj)

def create_membership_invitation_code(db, group, **kwargs):
    obj = create_membership_invitation(db, group, **kwargs)
    return stash_invitation(obj)

def stash_invitation(obj):
    # Compression enables squeezing friendship invitations into
    # OpenDHT.  There is a little bit of redundancy in the invitation,
    # mainly because the recipient's public key appears both in the
    # transmitted private key and in the transmitted member item.
    s = compress(obj.encode())
    return stash(s)

def fetch_invitation(code):
    s = fetch(code)
    return s and decode_invitation(decompress(s))

def stash(plaintext, ttl=7*24*3600):
    code = generate_code()

    key = strengthen(code)
    encryption_key = hmac.new(key, 'encryption key', sha1).digest()
    opendht_secret = hmac.new(key, 'opendht secret', sha1).digest()
    opendht_key = hmac.new(key, 'opendht key', sha1).digest()

    cipher = Cipher(encryption_key, IV=opendht_key)
    ciphertext = cipher.encrypt(plaintext)
    if len(ciphertext) > 1024:
        raise ValueError('Sorry, invitation is too big for OpenDHT.')

    try:
        result = opendht.put(opendht_key, ciphertext,
                             ttl=ttl, secret=opendht_secret)
    except opendht.Error, e:
        logging.debug('Stashing invitation: %s' % e)
        return None

    if opendht.interpret_result(result, 'Stashing invitation in OpenDHT'):
        return code

    return None

def fetch(code):
    key = strengthen(code)
    encryption_key = hmac.new(key, 'encryption key', sha1).digest()
    opendht_secret = hmac.new(key, 'opendht secret', sha1).digest()
    opendht_key = hmac.new(key, 'opendht key', sha1).digest()

    cipher = Cipher(encryption_key, IV=opendht_key)
    for ciphertext in opendht.get(opendht_key):
        result = opendht.rm(opendht_key, ciphertext, secret=opendht_secret)
        if result == 0:
            return cipher.decrypt(ciphertext)

    return None

def generate_code(size=8):
    # Alphabet from CryptoID:
    alphabet = "abcdefghijkmnopqrstuvwxyz3456789" #a-z0-9 except 'l',0,1,2
    s = ''.join(alphabet[ord(byte) % 32] for byte in urandom(size))

    pieces = []
    n = -(-size // 5)
    for k in range(n):
        i = int(k * size / float(n) + 0.5)
        j = int((k + 1) * size / float(n) + 0.5)
        pieces.append(s[i:j])
    return '-'.join(pieces)

def strengthen(code, count=100000, salt='-fusion-invitation'):
    key = code + salt
    for i in range(count):
        key = sha1(key).digest()
    return key

class Okay(Exception):
    pass

class Invitation(object):
    def accept(self, db):
        result = self.accept_new(db)
        return result == 'OK'

    def accept_new(self, db):
        try:
            return self._accept(db)
        except Unauthorized:
            return 'Unable to accept invitation.'

    def encode(self):
        return encode(self._encode())

class FriendshipInvitation(Invitation):
    def __init__(self, public_key, ciphertext,
                 private_key, member_item, secret, srs):
        self.public_key = _decode_identity(public_key)
        self.ciphertext = ciphertext
        self.private_key = _decode_identity(private_key)
        self.item = _decode_item(member_item)
        self.secret = secret
        self.srs = srs          # SRS = Secret Return Secret

        self.iid = hexlify(self.item.iid)
        assert self.item.key == ['member', self.private_key.fingerprint]

    def _accept(self, db):
        shared_secret = urandom(20)
        with db.exclusive_transaction():
            my_iid = db.get_my_iid()
            my_secret = db.get_my_domain_secret()
            my_fp = self.private_key.fingerprint

            your_iid = self.iid
            your_secret = self.secret
            your_fp = self.public_key.fingerprint

            if your_iid == my_iid:
                return 'Cannot accept a friendship invitation from yourself.'

            if your_iid in db.list_friends(my_iid):
                return 'Already friends.'

            db.put_item(self.item)
            db.add_fingerprint(my_iid, self.public_key)

            db.remember_private_key(your_iid, self.private_key)
            db.boomerang_domain_secret(your_iid, your_secret, my_fp)

            db.return_domain_secret(my_iid, my_secret, your_fp,
                                    your_iid, your_secret, self.srs)
            db.return_private_key(my_iid, your_iid, your_fp,
                                  self.ciphertext, your_secret)

            db.affirm_friendship(my_iid, your_fp,
                                 your_iid, my_fp, shared_secret)
            db.affirm_friendship(your_iid, my_fp,
                                 my_iid, your_fp, shared_secret)
            return 'OK'

    def _encode(self):
        return ['invitation',
                ['public_key', self.public_key.encode_public()],
                ['ciphertext', self.ciphertext],
                ['private_key', self.private_key.encode_private()],
                ['member_item', self.item.encode()],
                ['secret', self.secret],
                ['srs', self.srs]]

class MembershipInvitation(Invitation):
    def __init__(self, private_key, member_item, secret):
        self.private_key = _decode_identity(private_key)
        self.item = _decode_item(member_item)
        self.secret = secret

        self.iid = self.group = hexlify(self.item.iid)
        self.fingerprint = self.private_key.fingerprint
        assert self.item.key == ['member', self.fingerprint]

    def _accept(self, db):
        fp = self.fingerprint
        shared_secret = urandom(20)
        with db.exclusive_transaction():
            # XXX Clean up existing membership first?
            my_iid = db.get_my_iid()
            db.put_item(self.item)
            db.remember_private_key(self.group, self.private_key)
            db.boomerang_domain_secret(self.group, self.secret, fp)
            db.affirm_membership(my_iid, None, self.group, fp, shared_secret)
            db.affirm_membership(self.group, fp, my_iid, None, shared_secret)
            return 'OK'

    def _encode(self):
        return ['membership_invitation',
                ['private_key', self.private_key.encode_private()],
                ['member_item', self.item.encode()],
                ['secret', self.secret]]

def create_friendship_invitation(db, **kwargs):
    my_identity = generate()
    your_identity = generate()
    with db.transaction():
        my_iid = db.get_my_iid()
        secret = db.get_my_domain_secret()
        srs = db.get_secret(my_identity.fingerprint, 'encrypt domain secret')
        ciphertext = db.encrypt_private_key(my_identity)

    item = _create_member_item(db, my_iid, your_identity, kwargs)
    return FriendshipInvitation(my_identity, ciphertext,
                                your_identity, item, secret, srs)

def create_membership_invitation(db, group, **kwargs):
    group = hex(group)
    identity = generate()
    with db.transaction():
        assert db.get_type(group) == 'group'
        secret = db.get_domain_secret(group)

    item = _create_member_item(db, group, identity, kwargs)
    return MembershipInvitation(identity, item, secret)

def decode_invitation(invitation):
    data = decode(invitation)
    type = data.pop(0)
    fields = dict(data)
    if type == 'invitation':
        return FriendshipInvitation(**fields)
    elif type == 'membership_invitation':
        return MembershipInvitation(**fields)
    else:
        raise ValueError

def _create_member_item(db, domain, identity, info):
    try:
        with db.exclusive_transaction():
            db.add_fingerprint(domain, identity, info)
            item = db.get_item(domain, ['member', identity.fingerprint])
            raise Okay
    except Okay:
        return item

def _decode_identity(identity):
    return decode_identity(identity) if isinstance(identity, str) else identity

def _decode_item(item):
    return decode_item(item) if isinstance(item, str) else item

if __name__ == '__main__':
    import doctest
    doctest.testmod()
